<template>
	<view>
		<!-- <view class="wrapper bgw">
			<u-gap height="10" bgColor="#ffffff"></u-gap>
			<view class="flex">
				<view class="flex-1 ">
					<u-button text="下载Excel" type="success" @click="toExcel" :disabled="!excelUrl"></u-button>
				</view>
				<view class="ml10 mr10"></view>
				<view class="flex-1">
					<u-button text="分享图片" type="info" @click="extraImage"></u-button>
				</view>
			</view>
			<u-gap height="10" bgColor="#ffffff"></u-gap>
		</view>
		<u-line></u-line> -->
		<view class="wrapper bgw">
			<view class="blank20"></view>
			<view class="flex" style="align-items: baseline;">
				<!-- <view class="">
					显示：
				</view> -->
				<view class="flex-1">
					<u-checkbox-group v-model="fn_list" placement="row" @change="checkboxChange">
						<view class="flex" style="flex-wrap: wrap;">
							<template v-for="v in fn_config">
								<view class="" style="margin: 15upx;">
									<u-checkbox activeColor="#675f91" :label="v" :name="v" :disabled="true" v-if="v=='食材'"></u-checkbox>
									<u-checkbox activeColor="#675f91" :label="v" :name="v" v-else></u-checkbox>
								</view>
							</template>
						</view>
					</u-checkbox-group>
					<view class="blank20"></view>
					<view class="flex">
						<!-- <view class="flex-1">
							<u-button text="刷新表格" type="primary" @click="flashCanvas" size="small"></u-button>
						</view> 
						<view class="ml10 mr10"></view> -->
						<view class="flex-1 ">
							<u-button text="下载Excel" type="success" @click="toExcel" :disabled="!excelUrl" size="small"></u-button>
						</view>
						<view class="ml10 mr10"></view>
						<view class="flex-1">
							<u-button text="分享图片" type="primary" size="small" @click="extraImage"></u-button>
						</view>
					</view>
				</view>
			</view>
			<view class="blank20"></view>
		</view>
		<view class="blank20"></view>
		
		<view class="share-page-box" id="box" v-if="show" :style="{width: canvasWidth + 'px', height: canvasHeight + 'px' }">
			<wxml-to-canvas class="widget" :width="canvasWidth" :height="canvasHeight"></wxml-to-canvas>
		</view>
		<view class="wrapper" v-else :style="{width: canvasWidth + 'px', height: canvasHeight + 'px' }">
			<u-gap height="10"></u-gap>
			<view class="">
				{{msg}}
			</view>
		</view>
	</view>

</template>

<script>
	const {
		wxml,
		style
	} = require('@/util/DomData.js');
	import config from '@/common/config';
	import html2canvas from 'html2canvas';
	import {
		base64ToPath
	} from 'image-tools';
	import {
		share_po
	} from '@/common/api.js';
	// const Binding = uni.requireNativePlugin('bindingx');
	export default {
		data() {
			return {
				date: '',
				ids: [],
				fn_list: [],
				vals_list: [],
				loadingStatus: '',
				excelUrl: '',
				fn_config:['食材','数量','单位','单价','供应商','金额'],

				show: false, // 是否显示canvas
				canvasWidth: 320, // 默认canvas宽高
				canvasHeight: 480,
				screenWidth: null, // 设备宽度
				name: '',
				pic: '',
				chapter1: '',
				chapter2: '',
				widget: null,
				msg: '加载中，请稍等...', // 提示语

			}
		},
		methods: {
			checkboxChange(e){
				this.renderToCanvas(e);
				this.setFnListStorage(e);
			},
			setFnListStorage(fn_list){
				uni.setStorage({
					key: 'purchaseShareFnList',
					data: fn_list,
					success: function() {}
				});
			},
			getData() {
				let fnListStorage = false;
				try {
					fnListStorage = uni.getStorageSync('purchaseShareFnList') || false;
				} catch (e) {}
				uni.showLoading({
					title: '加载中'
				});
				this.loadingStatus = 'loading';
				share_po({
					po_ids_list: this.ids,
					format: 'png'
				}).then((res) => {
					let vals_list = res.result['图片'].vals_list
					if(!fnListStorage){
						this.fn_list = res.result['图片'].fn_list;
						this.setFnListStorage(this.fn_list);
					}else{
						this.fn_list = fnListStorage;
					}
					vals_list.forEach(v=>{
						for(let key in v){
							if(typeof v[key] == 'number'){
								v[key] = this.formatPrice(v[key]);
							}
						}
					})
					this.vals_list = vals_list;

					let url = res.result.url;
					this.excelUrl = config.webUrl + url;
					
					this.initCanvas();

					this.loadingStatus = 'end';
				}).catch(() => {

				}).finally(() => {
					uni.hideLoading();
					uni.stopPullDownRefresh();
				})
			},
			flashCanvas(){
				this.renderToCanvas();
			},
			toExcel() {
				let that = this;
				let url = this.excelUrl;
				uni.showLoading({
					title: '下载中'
				});
				wx.downloadFile({
					url: url, // 下载url
					success(res) {
						uni.hideLoading();
						// 下载完成后转发
						wx.shareFileMessage({
							filePath: res.tempFilePath,
							success() {},
							fail(err) {
								that.$u.toast('转发失败');
							}
						})
					},
					fail(err) {
						uni.hideLoading();
						that.$u.toast('下载失败');
					},
				})
			},
			// wxml 转 canvas
			renderToCanvas(fn_list) {
				if(!fn_list){
					fn_list = this.fn_list;
				}
				console.log('this.widget', this.widget)
				const _wxml = wxml(this.date, fn_list, this.vals_list);
				// console.log(_wxml);
				let ratio = 1/(fn_list.length);
				const _style = style(this.screenWidth, this.canvasWidth, this.canvasHeight,ratio);
				const p1 = this.widget.renderToCanvas({
					wxml: _wxml,
					style: _style
				})
				p1.then((res) => {
					console.log('图片生成成功');
					wx.hideLoading()
					// this.container = res
				}).catch((err) => {
					wx.hideLoading()
					console.log('生成失败')
				})
			},
			// 保存到朋友圈
			extraImage() {
				if (!this.show) {
					wx.showToast({
						title: '图片生成失败，无法分享',
						icon: 'none'
					})
					return
				}
				const p2 = this.widget.canvasToTempFilePath();
				let that = this;
				p2.then(result => {
					let path = result.tempFilePath;
					wx.showShareImageMenu({
					  path: path
					});
					return;
					
					wx.getSetting({
						success: res => {
							// 非初始化且未授权的情况，需要再次弹窗提示授权
							if (res.authSetting['scope.writePhotosAlbum'] != undefined && res.authSetting[
									'scope.writePhotosAlbum'] != true) {
								wx.showModal({
									title: '是否授权相册权限',
									content: '需要获取相册权限，请确认授权，否则无法使用相关功能',
									success: res => {
										if (res.confirm) {
											wx.openSetting({
												success: dataAu => {
													if (dataAu.authSetting["scope.writePhotosAlbum"] == true) {
														wx.showToast({
															title: '授权成功',
															icon: 'none',
															duration: 1000
														});
														that.saveIMg(path);
													} else {
														wx.showToast({
															title: '授权失败',
															icon: 'success',
															duration: 1000
														});
													}
												}
											});
										}
									}
								});
							} else {
								// 初始化且未授权，系统默认会弹窗提示授权
								// 非初始化且已授权，也会进入这里
								that.saveIMg(path);
							}
						}
					});
				})
			},
			// 保存到相册
			async saveIMg(tempFilePath) {
				wx.saveImageToPhotosAlbum({
					filePath: tempFilePath,
					success: async (res) => {
						wx.showModal({
							content: '图片已保存，分享给好友吧！',
							showCancel: false,
							confirmText: '好的',
							confirmColor: '#333',
							success: function(res) {
								wx.navigateBack({
									//返回
									delta: 1
								});
							},
							fail: function(res) {
								console.log('res', res);
							}
						});
					},

					fail: function(res) {
						wx.showToast({
							title: '您取消了授权',
							icon: 'none',
							duration: 2000
						})
					}
				});
			},
			initCanvas(){
				// 获取设备信息
				wx.getSystemInfo({
					success: (res) => {
						this.screenWidth = res.screenWidth
				
						this.canvasWidth = this.screenWidth * 1;
						// this.canvasHeight = this.screenWidth * 1;
						let canvasHeight = this.vals_list.length*35+70;
						this.canvasHeight = canvasHeight;
						console.log('screenWidth', this.screenWidth)
						this.show = true
						// 数字容器宽度 动态设置 
						setTimeout(() => {
							wx.showLoading({
								title: '图片生成中...'
							})
							this.widget = this.selectComponent('.widget')
							this.renderToCanvas()
						}, 1000)
					}
				});
			}
		},
		onLoad(d) {
			this.date = d.date || '2020-10-10'
			if (!d.ids) {
				d.ids = '8,6,7';
			}
			let ids = d.ids.split(',');
			ids.forEach(v => {
				this.ids.push(Number(v));
			})
			// console.log(ids);
			// this.ids = [43];
			this.getData();
		},
		onShow() {

		},
		onReady() {

		},
		onShareAppMessage(res) {
			let ids = this.ids.join(',');
			return {
				title: '采购信息',
				path: '/pagesA/purchaseShare/purchaseShareWx?date=' + this.date + '&ids=' + ids
			}
		}
	}
</script>

<style>
	.col-item {
		padding: 15upx 20upx;
	}
</style>